const express = require("express");
const router = express.Router();
const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");
const keys = require("../../config/keys");
const passport = require("passport");
const User = require("../../models/User");

// @route  GET api/users/test
// @desc   返回的请求的json数据
// @access public
router.get("/test", (req, res) =>
  res.json({ success: true, message: "登录成功" })
);

// @route  POST api/users/register
// @desc   用户注册
// @access public
router.post("/register", async (req, res) => {
  try {
    const { name, phone, password } = req.body;
    if (await User.findOne({ phone })) {
      return res
        .status(400)
        .json({ success: false, message: "手机号已被注册!" });
    }

    const hashedPassword = await bcrypt.hash(password, 10);
    const newUser = new User({
      name,
      phone,
      password: hashedPassword,
    });
    await newUser.save();

    res.json({ success: true, message: "用户注册成功!", user: newUser });
  } catch (error) {
    console.error(error);
    res
      .status(500)
      .json({ success: false, message: "注册失败!", error: error.message });
  }
});

// @route  POST api/users/login
// @desc   用户登录并返回token
// @access public
router.post("/login", async (req, res) => {
  try {
    const { phone, password } = req.body;
    const user = await User.findOne({ phone });
    if (!user || !(await bcrypt.compare(password, user.password))) {
      return res
        .status(400)
        .json({ success: false, message: "手机号或密码错误!" });
    }

    const payload = {
      id: user.id,
      name: user.name,
      avatar: user.avatar,
      identity: user.identity,
    };
    const token = jwt.sign(payload, keys.secretOrKey, { expiresIn: 36000000 });

    // 获取用户的完整信息
    const fullUser = await User.findById(user.id).select("-password"); // Exclude password

    res.json({
      success: true,
      message: "登录成功!",
      token: "Bearer " + token,
      user: fullUser,
    });
  } catch (error) {
    console.error(error);
    res
      .status(500)
      .json({ success: false, message: "登录失败!", error: error.message });
  }
});

// @route  GET api/users/current
// @desc   返回当前用户
// @access private
router.get(
  "/current",
  passport.authenticate("jwt", { session: false }),
  async (req, res) => {
    try {
      const fullUser = await User.findById(req.user.id).select("-password"); // Exclude password
      res.json({ success: true, message: "获取用户信息成功!", user: fullUser });
    } catch (error) {
      console.error(error);
      res.status(500).json({
        success: false,
        message: "获取用户信息失败!",
        error: error.message,
      });
    }
  }
);

// @route  PUT api/users/update
// @desc   更新用户信息
// @access private
router.put(
  "/update",
  passport.authenticate("jwt", { session: false }),
  async (req, res) => {
    try {
      const updateUser = { ...req.body };
      const user = await User.findByIdAndUpdate(
        req.user.id,
        { $set: updateUser },
        { new: true }
      );
      res.json({ success: true, message: "用户信息更新成功!", user });
    } catch (error) {
      console.error(error);
      res.status(500).json({
        success: false,
        message: "用户信息更新失败!",
        error: error.message,
      });
    }
  }
);

// @route  DELETE api/users/delete
// @desc   删除用户
// @access private
router.delete(
  "/delete",
  passport.authenticate("jwt", { session: false }),
  async (req, res) => {
    try {
      await User.findByIdAndRemove(req.user.id);
      res.json({ success: true, message: "用户删除成功!" });
    } catch (error) {
      console.error(error);
      res.status(500).json({
        success: false,
        message: "用户删除失败!",
        error: error.message,
      });
    }
  }
);

// @route  GET api/users/all
// @desc   获取所有用户信息
// @access private (Administrator only)
router.get(
  "/all",
  passport.authenticate("jwt", { session: false }),
  async (req, res) => {
    if (req.user.identity !== "Administrator") {
      return res.status(403).json({ success: false, message: "没有权限!" });
    }

    try {
      const users = await User.find();
      res.json({ success: true, message: "获取所有用户信息成功!", users });
    } catch (error) {
      console.error(error);
      res.status(500).json({
        success: false,
        message: "获取用户信息失败!",
        error: error.message,
      });
    }
  }
);

// @route  DELETE api/users/:id
// @desc   删除指定用户
// @access private (Administrator only)
router.delete(
  "/:id",
  passport.authenticate("jwt", { session: false }),
  async (req, res) => {
    if (req.user.identity !== "Administrator") {
      return res.status(403).json({ success: false, message: "没有权限!" });
    }

    try {
      const user = await User.findByIdAndRemove(req.params.id);
      if (!user) {
        return res.status(404).json({ success: false, message: "用户不存在!" });
      }

      res.json({ success: true, message: "用户删除成功!" });
    } catch (error) {
      console.error(error);
      res.status(500).json({
        success: false,
        message: "用户删除失败!",
        error: error.message,
      });
    }
  }
);

// @route  PUT api/users/:id
// @desc   更新指定用户信息
// @access private (Administrator only)
router.put(
  "/:id",
  passport.authenticate("jwt", { session: false }),
  async (req, res) => {
    if (req.user.identity !== "Administrator") {
      return res.status(403).json({ success: false, message: "没有权限!" });
    }

    try {
      const updateUser = { ...req.body };
      const user = await User.findByIdAndUpdate(
        req.params.id,
        { $set: updateUser },
        { new: true }
      );
      if (!user) {
        return res.status(404).json({ success: false, message: "用户不存在!" });
      }

      res.json({ success: true, message: "用户信息更新成功!", user });
    } catch (error) {
      console.error(error);
      res.status(500).json({
        success: false,
        message: "用户信息更新失败!",
        error: error.message,
      });
    }
  }
);

module.exports = router;
